<template>
  <div class="mainsu">
    <div class="main_spac1">
      <div class="main_white padding10">
        <div class="mainor_form">
          <el-form
            :inline="true"
            :model="form"
            class="demo-form-inline"
            ref="userListFrom"
            label-width="90px"
            id="form"
          >
            <el-form-item label="配送日期：" prop="send_time">
              <el-date-picker
                style="width: 220px"
                v-model="form.send_time"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="yyyy-MM-dd"
                @change="changePicker"
              >
              </el-date-picker>
            </el-form-item>
            <el-form-item label="商品分类：" prop="category_id" class="wid220">
              <el-cascader
                v-model="form.category_id"
                :options="options"
                :props="defaultProps"
                @change="getList"
              ></el-cascader>
            </el-form-item>
            <el-form-item label="商品名称：" prop="goods_spu_id">
              <change-goods-input
                ref="changeGoodsInput"
                @clear="
                  () => {
                    this.form.goods_spu_id = '';
                  }
                "
                @sendValue="
                  (data) => {
                    this.form.goods_spu_id = data.id;
                  }
                "
              ></change-goods-input>
              <!-- <el-input
                v-model.trim="form.name"
                placeholder="商品名称"
                clearable
                class="wid220"
              ></el-input> -->
            </el-form-item>
            <MainFormBtn @reset="reset" @getSearchFor="getArticleList" :loading="listLoading" :showBtn="moredata">
              <el-button v-print="printObj">打印</el-button>
            </MainFormBtn>
            <div class="more el-form-item" @click="more">
              <span>更多</span>
              <i :class="[{ on: moredata }, ' el-icon-arrow-down']"></i>
            </div>
            <div class="clearfix"></div>
            <el-collapse-transition>
              <div v-show="moredata">
                <!-- <el-form-item label="仓库" prop="name1">
                  <el-input
                    v-model.trim="form.name1"
                    placeholder="仓库"
                    clearable
                    class="wid220"
                  ></el-input>
                </el-form-item> -->
                <el-form-item label="用户分组：" prop="group_id">
                  <el-select
                    v-model.trim="form.group_id"
                    placeholder="用户分组"
                    class="wid220"
                  >
                    <el-option label="所有" value=""></el-option>
                    <el-option
                      v-for="(group, index) in searchFormData.group"
                      :key="index"
                      :label="group"
                      :value="index"
                    ></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="用户区域：" prop="region_id">
                  <el-select
                    v-model.trim="form.region_id"
                    multiple
                    collapse-tags
                    placeholder="用户区域"
                    class="wid220"
                  >
                    <el-option label="所有" value="" :disabled="Boolean(!form.region_id.includes('') && form.region_id.length)"></el-option>
                    <el-option
                      v-for="(region, index) in searchFormData.region"
                      :key="index"
                      :label="region"
                      :value="index"
                      :disabled="form.region_id.includes('')"
                    ></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="配送时间：" prop="send_time_id">
                  <el-select
                    v-model.trim="form.send_time_id"
                    placeholder="配送时间"
                    class="wid220"
                  >
                    <el-option label="所有" value=""></el-option>
                    <el-option
                      v-for="(send_time_list, index) in searchFormData.send_time_list"
                      :key="index"
                      :label="send_time_list"
                      :value="parseInt(index)"
                    ></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="配送线路：" prop="line_id">
                  <el-select
                    v-model.trim="form.line_id"
                    placeholder="配送线路"
                    class="wid220"
                  >
                    <el-option label="所有" value=""></el-option>
                    <el-option
                      v-for="(line, index) in searchFormData.line"
                      :key="index"
                      :label="line"
                      :value="index"
                    ></el-option>
                  </el-select>
                </el-form-item>
                <div class="clearfix"></div>
                <el-form-item label=" ">
                  <MainFormBtn class="btn-bottom" @reset="reset" @getSearchFor="getArticleList" :loading="listLoading" :showBtn="!moredata">
                    <el-button v-print="printObj">打印</el-button>
                  </MainFormBtn>
                </el-form-item>
              </div>
            </el-collapse-transition>
          </el-form>
        </div>
        <div class="main-controls-wrap mg-b-10 mg-t-0 height-42">
          <div>
            <el-button @click="mainor_qr">置顶</el-button>
            <el-button v-repeatClick @click="submitTime">导出明细</el-button>
            <el-button @click="export_all">导出汇总</el-button>
            <el-popover placement="bottom" trigger="hover">
                <div class="order_dervie">
                  <span
                    @click="export_table(1)"
                    class="order_dervie_content"
                    >二维表详情</span
                  >
                  <span
                    @click="export_table(2)"
                    class="order_dervie_content"
                    >子账号二维表</span
                  >
                </div>
                <el-button slot="reference">导出二维表</el-button>
              </el-popover>
          </div>
        </div>
        <div id="table" class="main_table">
          <el-table
            ref="multipleTable"
            v-loading="listLoading"
            :data="list"
            element-loading-text="加载中"
            fit
            border
            highlight-current-row
            :row-class-name="getRowClass"
            @expand-change="expandChange"
            :height="borderHeight - 6"
            :header-cell-class-name="this.$verticaline"
            :header-cell-style="tableHeightStyle"
            @header-dragend="changeTableWidth"
            @row-click="rowDblclick"
          >
            <el-table-column type="expand" class-name="main_hei">
              <!-- <template #header>
                <div @click="expandALL" style="cursor: pointer">
                  <i
                    style="font-size: 18px; font-weight: bold"
                    :class="
                      is_expand ? 'el-icon-arrow-down' : 'el-icon-arrow-right'
                    "
                  ></i>
                </div>
              </template> -->
              <template slot-scope="props">
                <div v-loading="props.row.loading">
                  <el-table
                    :ref="'expandchild' + props.$index"
                    :data="props.row.orderList"
                    class="mainex_ta"
                    fit
                    border
                    :row-class-name="getRowClass"
                    :highlight-current-row="false"
                    max-height="300"
                    :header-cell-class-name="$verticaline"
                    @header-dragend="changeTableWidth"
                  >
                    <el-table-column width="40" align="right" />
                    <el-table-column
                      label="订单号"
                      prop="order_sn"
                      :width="tableWidth[hash+'order_sn'] || 180"
                      show-overflow-tooltip
                    />
                    <el-table-column
                      label="用户名称"
                      prop="nickname"
                      :width="tableWidth[hash+'nickname'] || 160"
                      show-overflow-tooltip
                    />
                    <el-table-column
                      label="下单数量"
                      prop="order_num"
                      :width="tableWidth[hash+'order_num'] || 120"
                      show-overflow-tooltip
                    />
                    <el-table-column
                      label="下单单价"
                      prop="order_price"
                      :width="tableWidth[hash+'order_price'] || 120"
                      show-overflow-tooltip
                    />
                    <el-table-column
                      label="下单金额"
                      prop="order_money"
                      :width="tableWidth[hash+'order_money'] || 120"
                      show-overflow-tooltip
                    />
                    <el-table-column
                      label="配送数量"
                      prop="sort_num"
                      :width="tableWidth[hash+'sort_num'] || 120"
                      show-overflow-tooltip
                    />
                    <el-table-column
                      label="配送单价"
                      prop="sort_price"
                      :width="tableWidth[hash+'sort_price'] || 120"
                      show-overflow-tooltip
                    />
                    <el-table-column
                      label="配送金额"
                      prop="send_money"
                      :width="tableWidth[hash+'send_money'] || 120"
                      show-overflow-tooltip
                    />
                    <el-table-column
                      label="退货数量"
                      prop="return_num"
                      :width="tableWidth[hash+'return_num'] || 120"

                      show-overflow-tooltip
                    />
                    <el-table-column
                      label="退货金额"
                      prop="return_money"
                      :width="tableWidth[hash+'return_money'] || 120"
                      show-overflow-tooltip
                    />
                    <el-table-column
                      label="实配送金额"
                      prop="really_money"
                      :width="tableWidth[hash+'really_money'] || 140"
                      show-overflow-tooltip
                    />
                    <el-table-column
                      label="备注"
                      prop="remark"
                      min-width="100"
                      show-overflow-tooltip
                      :resizable="false"
                    />
                  </el-table>
                  <div 
                    class="flex-center mg-t-10 cursor" 
                    v-if="list[props.$index].isMore"
                    @click="getOrderMore(props.row)"
                  >
                    加载更多<i class="el-icon-arrow-down mg-l-10"></i>
                  </div>
                </div>
              </template>
            </el-table-column>

            <!-- <el-table-column type="selection" /> -->
            <el-table-column 
              label="序号"
              prop="sn"
              :width="tableWidth[hash+'number'] || 70"
            />
            <el-table-column
              label="商品名称"
              prop="name"
              show-overflow-tooltip
              :width="tableWidth[hash+'name'] || 200"
            />
            <el-table-column label="检测序号" prop="goods_spu_id" 
            :width="tableWidth[hash+'goods_spu_id'] || 150"/>
            <el-table-column
              label="单位"
              prop="unit"
              show-overflow-tooltip
              :width="tableWidth[hash+'unit'] || 100"
            />

            <el-table-column
              label="分类"
              prop="category_name"
              show-overflow-tooltip
              :width="tableWidth[hash+'category_name'] || 160"
            />
            <el-table-column
              label="市场价"
              prop="market_price"
              sortable
              :sort-method="(a, b) => { return a.market_price - b.market_price; }"
              show-overflow-tooltip
              :width="tableWidth[hash+'market_price']"
            />
            <el-table-column
              label="库存"
              prop="inventory_num"
              show-overflow-tooltip
              :width="tableWidth[hash+'inventory_num']"
            />
            <el-table-column
              label="下单总量"
              prop="order_num"
              :width="tableWidth[hash+'order_num']"
              show-overflow-tooltip
            />
            <el-table-column
              label="下单总额"
              prop="order_money"
              show-overflow-tooltip
              :width="tableWidth[hash+'order_money']"
            >
              <template slot-scope="scope">
                {{ parseFloat(scope.row.order_money) | twoPlace }}
              </template>
            </el-table-column>
            <el-table-column
              label="配送总量"
              prop="send_num"
              show-overflow-tooltip
              :width="tableWidth[hash+'send_num']"
            />
            <el-table-column
              label="配送总额"
              prop="send_money"
              show-overflow-tooltip
              :width="tableWidth[hash+'send_money']"
            />
            <el-table-column
              label="退货总量"
              prop="return_num"
              show-overflow-tooltip
              :width="tableWidth[hash+'return_num']"
            />
            <el-table-column
              label="退货总额"
              prop="return_money"
              show-overflow-tooltip
              :width="tableWidth[hash+'return_money']"
            />
            <el-table-column
              label="实配送总额"
              prop="really_money"
              show-overflow-tooltip
              :width="tableWidth[hash+'really_money']"
            />
          </el-table>
          <div class="boxdq marginTop10">
            <div class="main_num_l"></div>
            <div class="main_num_r">
              <MainPagination
                :current-page="current.page"
                :page-size="current.size"
                :page-sizes="[10, 20, 30, 50, 100]"
                layout="total, sizes, prev, pager, next, jumper"
                :total="totalCount"
                background
                @size-change="changeSize"
                @current-change="changePage"
              />
            </div>
          </div> 
        </div>
      </div>
    </div>
    <!-- 导出 -->
    <el-dialog
      title="导出"
      width="380px"
      class="main_dialog"
      :visible.sync="dialogFormVisible"
    >
      <el-form :model="form" ref="form">
        <el-form-item
          label="配送日期："
          prop="oldPass"
          label-width="90"
        >
          <el-date-picker
            style="width: 260px"
            v-model="sendTime"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd"
            @change="changeSendTime"
          >
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitTime">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mixins } from "@/mixins/index.js";
import {
  orderList_index,
  orderSummary_export_detail,
  orderSummary_export_all,
  orderSummary_table,
  orderListSearch_condition,
  orderListStatic_goods,
  orderListStatic_orders,
} from "@/api/order/orderSummary";
import { apiUrl, objKeySort, Md5, packApi } from "@/utils/public";
import { recursion, category, exportMethod } from "@/utils/index";
import { parseTime } from "@/utils/index";
import print from "vue-print-nb";

export default {
  mixins: [mixins],
  components: {},
  data() {
    return {
      parseTime,
      exportMethod,
      // 分页
      current: {
        page: 1,
        size: 20,
      },
      totalCount: 1,
      // 列表数据
      list: [],
      listLoading: false,
      // 搜索
      form: {
        goods_spu_id: "",
        pid: "",
        category_id: [],
        send_time: [],
        send_time_id: null,
        line_id: null,
        group_id: null,
        region_id: [],
      },
      formsp: {
        value: "",
      },
      // 更多
      moredata: false,
      // 分类
      options: [],
      defaultProps: {
        children: "selfNext",
        label: "title",
        value: "id",
        checkStrictly: true,
      },
      printObj: {
        id: "table",
      },
      is_expand: false,

      // 分页
      orderForm: {
        size: 1,
        pageSize: 20,
      },
      total: 0,
      sendTime: null,
      dialogFormVisible: false,
      // 搜索数据
      searchFormData: {
        categoryList: [],
        group: {},
        line: {},
        region: {},
        send_time_list: [],
      },
      pageSize: 200
    };
  },
  created() {
    const now = new Date();
    const year = now.getFullYear();
    const month = ("0" + (now.getMonth() + 1)).slice(-2);
    const day = ("0" + now.getDate()).slice(-2);
    const formattedTime = year + "-" + month + "-" + day;
    this.form.send_time = [formattedTime, formattedTime];
    // 列表
    this.getNumerical(200);
    this.getSearchForm();
    this.getList();
  },
  directives: {
    print,
  },
  methods: {
    rowDblclick(row) {
      this.$refs.multipleTable.toggleRowExpansion(row)
    },
    // 敲击回车键
    startGetting() {
      this.getArticleList();
    },
    // 置顶
    mainor_qr() {
      if (this.$refs.changeGoodsInput) {
        let targetName = this.$refs.changeGoodsInput.name;
        if(!targetName) return;
        // 将 this.list.list 排序，将 name 等于 targetName 的项移到最前面
        this.list.sort((a, b)=> {
          // 如果 a.name 等于 targetName，将其置顶（返回 -1）
          if (a.name.includes(targetName)) return -1;
          // 如果 b.name 等于 targetName，将其置顶（返回 1）
          if (b.name.includes(targetName)) return 1;
          // 其他情况不做任何改变，保持原有顺序（返回 0）
          return 0;
        });
      }
    },
    // 判断表格是否有子项，无子项不显示展开按钮
    getRowClass(row) {
      row.row.index = row.rowIndex;
      if (row.row.order_list) {
        if (row.row.order_list.length === 0) {
          return "row-expand-cover";
        }
      }
    },
    // 监听展开行
    expandChange(rows, row) {
      if(!rows.orderList.length && !rows.loading) {
        this.getOrderChildrenList(rows);
      }
    },
    // 监听一级是否勾选
    onTableSelect(rows, row) {
      // console.log(rows, row)
      row.checked = !row.checked;
      if (row.checked) {
        row.order_list.forEach((m) => {
          if (this.$refs["expandchild" + row.index]) {
            this.$refs["expandchild" + row.index].toggleRowSelection(m, true);
          }
          m.checked = true;
        });
      } else {
        row.order_list.forEach((i) => {
          if (this.$refs["expandchild" + row.index]) {
            this.$refs["expandchild" + row.index].clearSelection();
          }
          i.checked = false;
        });
      }
    },
    // 搜索
    getArticleList() {
      this.current.page = 1;
      this.getList();
    },
    reset() {
      this.$refs["userListFrom"].resetFields();
      if (this.$refs["changeGoodsInput"]) {
        this.$refs["changeGoodsInput"].name = "";
      }
      const now = new Date();
      const year = now.getFullYear();
      const month = ("0" + (now.getMonth() + 1)).slice(-2);
      const day = ("0" + now.getDate()).slice(-2);
      const formattedTime = year + "-" + month + "-" + day;
      this.form.send_time = [formattedTime, formattedTime];
      this.getArticleList();
    },
    // 分页
    changeSize(pageSize) {
      this.current.size = pageSize;
      this.getList();
    },
    changePage(page) {
      this.current.page = page;
      this.getList();
    },
    // 更多
    more() {
      this.moredata = !this.moredata;
    },
    // 列表
    getList() {
      this.listLoading = true;
      let data = packApi({
        ...this.list_form(),
        ...this.current,
      });
      orderListStatic_goods(data).then((res) => {
        this.listLoading = false;
        if (res.errcode == 0) {
          this.list = res.data.list.map((e) => {
            e.checked = false;
            e.loading = false;
            e.page = 1;
            e.isMore = true;
            e.orderList = [];
            return e;
          });
          this.is_expand = false;
          this.totalCount = res.data.total;
        } else {
          this.$message.error(res.errmsg);
        }
      });
    },
    // 加载更多数据
    getOrderMore(row) {
      row.page++;
      this.getOrderChildrenList(row);
    },
    getOrderChildrenList(row) {
      row.loading = true;
      let data = packApi({
        ...this.list_form(),
        page: row.page,
        size: this.pageSize,
        goods_spu_id: row.goods_spu_id,
      });
      orderListStatic_orders(data).then(res=> {
        if(res.errcode == 0){
          if(!res.data.length) {
            this.$message.success("没有更多数据了");
            row.isMore = false;
            return;
          }
          row.orderList = row.orderList.concat(res.data);
          row.loading = false;
          if(res.data.length != this.pageSize) row.isMore = false;
        }else {
          this.$message.error(res.errmsg);
        }
      });
    },
    changePicker(val) {
      if(!val) return;
      let start = new Date(val[0]).getTime();
      let end = new Date(val[1]).getTime();
      let diff = start - end;
      if (Math.abs(diff) > 3600 * 1000 * 24 * 30) {
        this.$message.warning("选择时间跨度不能超过30日");
        this.form.send_time = [];
      } else {
        this.getList();
      }
     },
    // 搜索条件
    getSearchForm() {
      orderListSearch_condition(packApi()).then(res=> {
        if(res.errcode == 0) {
          this.searchFormData = res.data;
          this.options = recursion(res.data.categoryList, true);
        }else {
          this.$message.error(res.errmsg);
        }
      })
    },
    list_form() {
      let form = JSON.parse(JSON.stringify(this.form));
      form.pid = form.category_id[0] ? form.category_id[0] : "";
      form.category_id = category(form.category_id);
      form.send_time = form.send_time.join("_");
      form.region_id = form.region_id.join(",");
      return form;
    },
    // 展开全部
    expandALL() {
      this.is_expand = !this.is_expand;
      this.list.list.forEach((e) => {
        this.$refs.multipleTable.toggleRowExpansion(e, this.is_expand);
      });
    },
    // 导出明细
    export_detail() {
      // this.dialogFormVisible = !this.dialogFormVisible
    },
    // 导出汇总
    export_all() {
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name, this.list_form())) +
              apiUrl().appsecret
          ),
        },
        apiUrl().name,
        this.list_form()
      );
      const notify = this.$notify.info({
        title: "开始导出...",
        type: "success",
        duration: 0,
      });
      orderSummary_export_all(data)
        .then((res) => {
          this.exportMethod(res, "订单汇总", notify);
        })
        .catch((err) => {
          this.$message.error("导出失败");
        });
    },
    //二维表导出
    export_table(type) {
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name, this.list_form(),{type})) +
              apiUrl().appsecret
          ),
        },
        apiUrl().name,
        this.list_form(),
        {type}
      );
      const notify = this.$notify.info({
        title: "开始导出...",
        type: "success",
        duration: 0,
      });
      orderSummary_table(data)
        .then((res) => {
          this.exportMethod(res, "订单汇总二维表", notify);
        })
        .catch((err) => {
          this.$message.error("导出失败");
        });
    },
    changeSendTime(val) {
      let start = new Date(val[0]).getTime();
      let end = new Date(val[1]).getTime();
      let diff = start - end;
      if (Math.abs(diff) > 3600 * 1000 * 24 * 29) {
        this.$message.warning("选择时间跨度不能超过30天！");
        this.sendTime = null;
      }
    },
    submitTime() {
      if(!this.form.send_time || !this.form.send_time.length) {
        return this.$message.warning('请选择配送日期')
      }
      let data = {
        ...this.list_form(),
        type: 6, // 代表订单-订单汇总-导出明细
        send_time: this.form.send_time.join('_')
      };
      this.$store.dispatch("user/exportData", data)
      this.sendTime = null;
    }
  },
};
</script>
<style lang="scss" scoped>
@import "@/styles/variables.scss";
.cursor {
  cursor: pointer;
}
/deep/ .el-dialog__body {
  padding-bottom: 10px;
  min-height: 0;
  .el-form-item__label {
    color: #000000;
  }
}
.cursor {
  cursor: pointer;
}
.main_dialog {
  /deep/.el-dialog__title {
    font-size: 18px;
    color: #000000;
  }
  /deep/.el-range-editor--small .el-range-separator {
    position: static;
  }
  /deep/.el-range-editor .el-range-input {
    position: static;
  }
}
.mainsu {
  .mainor_form form {
    width: 100%;
  }
  .mainor_ter {
    margin-top: 4px;
    /deep/.el-button {
      margin-left: 5px;
    }
    a {
      white-space: nowrap;
      border: 1px solid $menuActiveText;
      background-color: $menuActiveText;
      padding: 7px 10px;
      color: $white;
      -webkit-appearance: none;
      text-align: center;
      -webkit-box-sizing: border-box;
      box-sizing: border-box;
      -webkit-transition: 0.1s;
      transition: 0.1s;
      font-weight: 500;
      font-size: $font_14;
      border-radius: 4px;
    }
  }
}
#table {
  position: relative;
}
.print {
  position: absolute;
  right: 0;
  margin-top: -40px;
  justify-content: flex-end;
  z-index: 1;
}

/deep/.el-form-item--small.el-form-item {
  margin-bottom: 10px;
}

/deep/.el-range-editor--small .el-range__close-icon,
.el-range-editor--small .el-range__icon {
  margin-right: 13px;
}

.order_dervie {
  width: auto;
  display: flex;
  flex-direction: column;
  align-items: center;
  cursor: pointer;

  span:hover {
    color: #03a98e;
    cursor: pointer;
  }

  .order_dervie_content {
    margin-bottom: 8px;
  }
}
</style>
